package com.xlh.support.backup.controller;

import com.xlh.aop.PreAcquireLock;
import com.xlh.common.Result;
import com.xlh.support.backup.po.BackupSwitchUpdatePO;
import com.xlh.support.backup.service.BackupService;
import com.xlh.support.backup.vo.AutoBackupVO;
import com.xlh.support.backup.vo.BackupVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import static com.xlh.support.backup.constant.BackupConstant.BACKUP;
import static com.xlh.support.backup.constant.BackupConstant.BACKUP_MESSAGE;

/**
 * @author cheer
 */
@Api("备份")
@RestController
@RequestMapping("/backup")
public class BackupController {

    @Autowired
    private BackupService backupService;

    @ApiOperation("查询备份基本信息")
    @GetMapping("/get")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result<BackupVO> queryAutoBackupSwitch() {
        BackupVO backupVO = backupService.queryAutoBackupSwitch();
        return Result.success(backupVO);
    }

    @ApiOperation("保存自动备份开关")
    @PostMapping("/switch")
    @PreAuthorize("@permissionValidator.isAdmin()")
    @PreAcquireLock(value = BACKUP, message = BACKUP_MESSAGE)
    public Result<AutoBackupVO> updateAutoBackupSwitch(@RequestBody @Valid BackupSwitchUpdatePO backupSwitchUpdatePO) {
        AutoBackupVO autoBackupVO = backupService.updateAutoBackupSwitch(backupSwitchUpdatePO.getSwitchOn());
        return Result.success(autoBackupVO);
    }

    @ApiOperation("手动备份")
    @PostMapping("/manual")
    @PreAuthorize("@permissionValidator.isAdmin()")
    @PreAcquireLock(value = BACKUP, message = BACKUP_MESSAGE)
    public Result manualBackup() {
        backupService.manualBackup();
        return Result.success();
    }

    @ApiOperation("还原备份")
    @PostMapping("/recover")
    @PreAuthorize("@permissionValidator.isAdmin()")
    @PreAcquireLock(value = BACKUP, message = BACKUP_MESSAGE)
    public Result recoverBackup() {
        backupService.recoverBackup();
        return Result.success();
    }
}
